<script setup lang="ts">
import type {
  CapabilityFacet,
  CapabilityInterface,
  Specification,
} from '#/api/resource-center/types';

import { computed, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import { message } from 'ant-design-vue';

// Props
interface Props {
  capability?: CapabilityFacet;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  update: [capability: CapabilityFacet];
}>();

// 响应式数据
const interfaceModalVisible = ref(false);
const specificationModalVisible = ref(false);
const evaluationModalVisible = ref(false);
const editingInterface = ref<CapabilityInterface | null>(null);
const editingSpecification = ref<null | Specification>(null);

// 表单数据
const interfaceForm = reactive({
  id: '',
  name: '',
  type: 'REST',
  endpoint: '',
  method: 'GET',
  authType: 'NONE',
  inputSchema: '',
  outputSchema: '',
});

const specificationForm = reactive({
  id: '',
  name: '',
  version: '',
  status: 'DRAFT',
  description: '',
  metrics: [] as string[],
});

// 计算属性
const capability = computed(
  () =>
    props.capability || {
      category: 'BUSINESS',
      definition: { id: '', code: '' },
      interfaces: [],
      specifications: [],
    },
);

// 评估相关数据
const evaluationColumns = [
  { title: '评估项', dataIndex: 'item', key: 'item' },
  { title: '权重', dataIndex: 'weight', key: 'weight' },
  { title: '得分', dataIndex: 'score', key: 'score' },
  { title: '状态', dataIndex: 'status', key: 'status' },
];

const evaluationData = [
  { item: '响应时间', weight: '20%', score: '85分', status: '良好' },
  { item: '吞吐量', weight: '15%', score: '92分', status: '优秀' },
  { item: '错误率', weight: '25%', score: '88分', status: '良好' },
  { item: '可用性', weight: '20%', score: '95分', status: '优秀' },
  { item: '安全性', weight: '20%', score: '82分', status: '良好' },
];

// 方法
const getCategoryColor = (category?: string) => {
  const colorMap: Record<string, string> = {
    BUSINESS: 'green',
    TECHNICAL: 'blue',
    OPERATIONAL: 'orange',
  };
  return colorMap[category || ''] || 'default';
};

const getCategoryLabel = (category?: string) => {
  const labelMap: Record<string, string> = {
    BUSINESS: '业务能力',
    TECHNICAL: '技术能力',
    OPERATIONAL: '运营能力',
  };
  return labelMap[category || ''] || category || '未知';
};

const getInterfaceTypeColor = (type?: string) => {
  const colorMap: Record<string, string> = {
    REST: 'green',
    GRAPHQL: 'purple',
    GRPC: 'blue',
    WEBSOCKET: 'orange',
    EVENT: 'cyan',
  };
  return colorMap[type || ''] || 'default';
};

const getInterfaceTypeLabel = (type?: string) => {
  const labelMap: Record<string, string> = {
    REST: 'REST API',
    GRAPHQL: 'GraphQL',
    GRPC: 'gRPC',
    WEBSOCKET: 'WebSocket',
    EVENT: '事件',
  };
  return labelMap[type || ''] || type || '未知';
};

const getSpecificationStatusColor = (status?: string) => {
  const colorMap: Record<string, string> = {
    DRAFT: 'default',
    REVIEW: 'orange',
    APPROVED: 'green',
    DEPRECATED: 'red',
  };
  return colorMap[status || ''] || 'default';
};

const getSpecificationStatusLabel = (status?: string) => {
  const labelMap: Record<string, string> = {
    DRAFT: '草稿',
    REVIEW: '评审中',
    APPROVED: '已批准',
    DEPRECATED: '已废弃',
  };
  return labelMap[status || ''] || status || '未知';
};

// 接口管理方法
const showAddInterfaceModal = () => {
  editingInterface.value = null;
  resetInterfaceForm();
  interfaceModalVisible.value = true;
};

const editInterface = (interfaceItem: CapabilityInterface) => {
  editingInterface.value = interfaceItem;
  interfaceForm.id = interfaceItem.id;
  interfaceForm.name = interfaceItem.name;
  interfaceForm.type = interfaceItem.type;
  interfaceForm.endpoint = interfaceItem.endpoint;
  interfaceForm.method = interfaceItem.method;
  interfaceForm.authType = interfaceItem.auth?.kind || 'NONE';
  interfaceForm.inputSchema = interfaceItem.inputSchema
    ? JSON.stringify(interfaceItem.inputSchema, null, 2)
    : '';
  interfaceItem.inputSchemaJSON.stringifyinterfaceItem.inputSchemaJSON
    .stringify;
  interfaceForm.outputSchema = interfaceItem.outputSchema
    ? JSON.stringify(interfaceItem.outputSchema, null, 2)
    : '';
  interfaceForm.outputSchemainterfaceItem.outputSchemaJSON
    .stringifyinterfaceItem.outputSchemaJSON.stringify;
  interfaceModalVisible.value = true;
};

const saveInterface = () => {
  if (!interfaceForm.id || !interfaceForm.name || !interfaceForm.endpoint) {
    message.error('请填写接口ID、名称和端点');
    return;
  }

  const newInterface: CapabilityInterface = {
    id: interfaceForm.id,
    name: interfaceForm.name,
    type: interfaceForm.type,
    endpoint: interfaceForm.endpoint,
    method: interfaceForm.method,
    auth:
      interfaceForm.authType === 'NONE'
        ? undefined
        : { kind: interfaceForm.authType },
    inputSchema: interfaceForm.inputSchema
      ? JSON.parse(interfaceForm.inputSchema)
      : undefined,
    outputSchema: interfaceForm.outputSchema
      ? JSON.parse(interfaceForm.outputSchema)
      : undefined,
  };

  const currentInterfaces = capability.value.interfaces || [];
  let newInterfaces: CapabilityInterface[];

  newInterfaces = editingInterface.value
    ? currentInterfaces.map((i) =>
        i.id === editingInterface.value!.id ? newInterface : i,
      )
    : [...currentInterfaces, newInterface];

  emit('update', { ...capability.value, interfaces: newInterfaces });
  message.success(editingInterface.value ? '接口更新成功' : '接口添加成功');
  interfaceModalVisible.value = false;
  resetInterfaceForm();
};

const cancelInterface = () => {
  interfaceModalVisible.value = false;
  resetInterfaceForm();
};

const resetInterfaceForm = () => {
  interfaceForm.id = '';
  interfaceForm.name = '';
  interfaceForm.type = 'REST';
  interfaceForm.endpoint = '';
  interfaceForm.method = 'GET';
  interfaceForm.authType = 'NONE';
  interfaceForm.inputSchema = '';
  interfaceForm.outputSchema = '';
};

const deleteInterface = (interfaceId: string) => {
  const newInterfaces =
    capability.value.interfaces?.filter((i) => i.id !== interfaceId) || [];
  emit('update', { ...capability.value, interfaces: newInterfaces });
  message.success('接口删除成功');
};

const testInterface = (interfaceItem: CapabilityInterface) => {
  message.info(`测试接口: ${interfaceItem.name}`);
};

// 规格管理方法
const showAddSpecificationModal = () => {
  editingSpecification.value = null;
  resetSpecificationForm();
  specificationModalVisible.value = true;
};

const editSpecification = (spec: Specification) => {
  editingSpecification.value = spec;
  specificationForm.id = spec.id;
  specificationForm.name = spec.name;
  specificationForm.version = spec.version;
  specificationForm.status = spec.status;
  specificationForm.description = spec.description || '';
  specificationForm.metrics = [...(spec.metrics || [])];
  specificationModalVisible.value = true;
};

const saveSpecification = () => {
  if (!specificationForm.id || !specificationForm.name) {
    message.error('请填写规格ID和名称');
    return;
  }

  const newSpecification: Specification = {
    id: specificationForm.id,
    name: specificationForm.name,
    version: specificationForm.version,
    status: specificationForm.status,
    description: specificationForm.description,
    metrics: specificationForm.metrics,
  };

  const currentSpecifications = capability.value.specifications || [];
  let newSpecifications: Specification[];

  newSpecifications = editingSpecification.value
    ? currentSpecifications.map((s) =>
        s.id === editingSpecification.value!.id ? newSpecification : s,
      )
    : [...currentSpecifications, newSpecification];

  emit('update', { ...capability.value, specifications: newSpecifications });
  message.success(editingSpecification.value ? '规格更新成功' : '规格添加成功');
  specificationModalVisible.value = false;
  resetSpecificationForm();
};

const cancelSpecification = () => {
  specificationModalVisible.value = false;
  resetSpecificationForm();
};

const resetSpecificationForm = () => {
  specificationForm.id = '';
  specificationForm.name = '';
  specificationForm.version = '';
  specificationForm.status = 'DRAFT';
  specificationForm.description = '';
  specificationForm.metrics = [];
};

const deleteSpecification = (specId: string) => {
  const newSpecifications =
    capability.value.specifications?.filter((s) => s.id !== specId) || [];
  emit('update', { ...capability.value, specifications: newSpecifications });
  message.success('规格删除成功');
};

const evaluateSpecification = (spec: Specification) => {
  message.info(`评估规格: ${spec.name}`);
};

// 评估方法
const showEvaluationModal = () => {
  evaluationModalVisible.value = true;
};

// 指标编辑器方法
const addMetric = () => {
  specificationForm.metrics.push('');
};

const removeMetric = (index: number) => {
  specificationForm.metrics.splice(index, 1);
};
</script>

<template>
  <div class="resource-capability">
    <!-- 能力管理头部 -->
    <div class="capability-header">
      <h3>能力管理</h3>
      <a-space>
        <a-button type="primary" @click="showAddInterfaceModal">
          <template #icon>
            <IconifyIcon icon="ant-design:plus-outlined" />
          </template>
          添加接口
        </a-button>
        <a-button @click="showEvaluationModal">
          <template #icon>
            <IconifyIcon icon="ant-design:thunderbolt-outlined" />
          </template>
          能力评估
        </a-button>
      </a-space>
    </div>

    <!-- 能力基本信息 -->
    <a-card title="能力基本信息" class="capability-card">
      <a-descriptions :column="2">
        <a-descriptions-item label="能力类别">
          <a-tag :color="getCategoryColor(capability?.category)">
            {{ getCategoryLabel(capability?.category) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="能力定义">
          {{ capability?.definition?.code || '未设置' }}
        </a-descriptions-item>
        <a-descriptions-item label="接口数量">
          {{ capability?.interfaces?.length || 0 }}
        </a-descriptions-item>
        <a-descriptions-item label="规格数量">
          {{ capability?.specifications?.length || 0 }}
        </a-descriptions-item>
      </a-descriptions>
    </a-card>

    <!-- 能力接口 -->
    <a-card title="能力接口" class="capability-card">
      <div class="interfaces-section">
        <a-empty
          v-if="!capability?.interfaces?.length"
          description="暂无接口定义"
        />

        <div v-else class="interfaces-list">
          <a-card
            v-for="interfaceItem in capability.interfaces"
            :key="interfaceItem.id"
            class="interface-card"
            size="small"
          >
            <template #title>
              <div class="interface-title">
                <span>{{ interfaceItem.name }}</span>
                <a-tag
                  :color="getInterfaceTypeColor(interfaceItem.type)"
                  size="small"
                >
                  {{ getInterfaceTypeLabel(interfaceItem.type) }}
                </a-tag>
              </div>
            </template>

            <div class="interface-info">
              <p><strong>端点:</strong> {{ interfaceItem.endpoint }}</p>
              <p><strong>方法:</strong> {{ interfaceItem.method }}</p>
              <p v-if="interfaceItem.auth">
                <strong>认证:</strong> {{ interfaceItem.auth.kind }}
              </p>
            </div>

            <div class="interface-actions">
              <a-button
                type="link"
                size="small"
                @click="editInterface(interfaceItem)"
              >
                编辑
              </a-button>
              <a-button
                type="link"
                size="small"
                @click="testInterface(interfaceItem)"
              >
                测试
              </a-button>
              <a-popconfirm
                title="确定要删除这个接口吗？"
                @confirm="deleteInterface(interfaceItem.id)"
              >
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </div>
          </a-card>
        </div>
      </div>
    </a-card>

    <!-- 能力规格 -->
    <a-card title="能力规格" class="capability-card">
      <div class="specifications-section">
        <a-button @click="showAddSpecificationModal" type="dashed" block>
          <IconifyIcon icon="ant-design:plus-outlined" />
          添加规格
        </a-button>

        <div
          v-if="capability?.specifications?.length"
          class="specifications-list"
        >
          <a-card
            v-for="spec in capability.specifications"
            :key="spec.id"
            class="specification-card"
            size="small"
          >
            <template #title>
              <div class="specification-title">
                <span>{{ spec.name }}</span>
                <a-tag
                  :color="getSpecificationStatusColor(spec.status)"
                  size="small"
                >
                  {{ getSpecificationStatusLabel(spec.status) }}
                </a-tag>
              </div>
            </template>

            <div class="specification-info">
              <p><strong>版本:</strong> {{ spec.version }}</p>
              <p><strong>描述:</strong> {{ spec.description }}</p>
              <p v-if="spec.metrics">
                <strong>指标:</strong> {{ spec.metrics.join(', ') }}
              </p>
            </div>

            <div class="specification-actions">
              <a-button
                type="link"
                size="small"
                @click="editSpecification(spec)"
              >
                编辑
              </a-button>
              <a-button
                type="link"
                size="small"
                @click="evaluateSpecification(spec)"
              >
                评估
              </a-button>
              <a-popconfirm
                title="确定要删除这个规格吗？"
                @confirm="deleteSpecification(spec.id)"
              >
                <a-button type="link" size="small" danger>删除</a-button>
              </a-popconfirm>
            </div>
          </a-card>
        </div>
      </div>
    </a-card>

    <!-- 添加/编辑接口模态框 -->
    <a-modal
      v-model:open="interfaceModalVisible"
      :title="editingInterface ? '编辑接口' : '添加接口'"
      width="800px"
      @ok="saveInterface"
      @cancel="cancelInterface"
    >
      <a-form :model="interfaceForm" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="接口ID" name="id">
              <a-input
                v-model:value="interfaceForm.id"
                placeholder="请输入接口ID"
                :disabled="!!editingInterface"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="接口名称" name="name">
              <a-input
                v-model:value="interfaceForm.name"
                placeholder="请输入接口名称"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="接口类型" name="type">
              <a-select
                v-model:value="interfaceForm.type"
                placeholder="请选择接口类型"
              >
                <a-select-option value="REST">REST API</a-select-option>
                <a-select-option value="GRAPHQL">GraphQL</a-select-option>
                <a-select-option value="GRPC">gRPC</a-select-option>
                <a-select-option value="WEBSOCKET">WebSocket</a-select-option>
                <a-select-option value="EVENT">事件</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="HTTP方法" name="method">
              <a-select
                v-model:value="interfaceForm.method"
                placeholder="请选择HTTP方法"
              >
                <a-select-option value="GET">GET</a-select-option>
                <a-select-option value="POST">POST</a-select-option>
                <a-select-option value="PUT">PUT</a-select-option>
                <a-select-option value="DELETE">DELETE</a-select-option>
                <a-select-option value="PATCH">PATCH</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="认证类型" name="authType">
              <a-select
                v-model:value="interfaceForm.authType"
                placeholder="请选择认证类型"
              >
                <a-select-option value="NONE">无认证</a-select-option>
                <a-select-option value="JWT">JWT</a-select-option>
                <a-select-option value="API_KEY">API Key</a-select-option>
                <a-select-option value="OAUTH2">OAuth2</a-select-option>
                <a-select-option value="BASIC">Basic Auth</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="端点" name="endpoint">
          <a-input
            v-model:value="interfaceForm.endpoint"
            placeholder="请输入端点路径"
          />
        </a-form-item>

        <a-form-item label="输入Schema" name="inputSchema">
          <a-textarea
            v-model:value="interfaceForm.inputSchema"
            placeholder="请输入输入Schema（JSON格式）"
            :rows="4"
          />
        </a-form-item>

        <a-form-item label="输出Schema" name="outputSchema">
          <a-textarea
            v-model:value="interfaceForm.outputSchema"
            placeholder="请输入输出Schema（JSON格式）"
            :rows="4"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 添加/编辑规格模态框 -->
    <a-modal
      v-model:open="specificationModalVisible"
      :title="editingSpecification ? '编辑规格' : '添加规格'"
      width="600px"
      @ok="saveSpecification"
      @cancel="cancelSpecification"
    >
      <a-form :model="specificationForm" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="规格ID" name="id">
              <a-input
                v-model:value="specificationForm.id"
                placeholder="请输入规格ID"
                :disabled="!!editingSpecification"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="规格名称" name="name">
              <a-input
                v-model:value="specificationForm.name"
                placeholder="请输入规格名称"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="版本" name="version">
              <a-input
                v-model:value="specificationForm.version"
                placeholder="请输入版本号"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态" name="status">
              <a-select
                v-model:value="specificationForm.status"
                placeholder="请选择状态"
              >
                <a-select-option value="DRAFT">草稿</a-select-option>
                <a-select-option value="REVIEW">评审中</a-select-option>
                <a-select-option value="APPROVED">已批准</a-select-option>
                <a-select-option value="DEPRECATED">已废弃</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="描述" name="description">
          <a-textarea
            v-model:value="specificationForm.description"
            placeholder="请输入规格描述"
            :rows="3"
          />
        </a-form-item>

        <a-form-item label="评估指标" name="metrics">
          <div class="metrics-editor">
            <a-button @click="addMetric" type="dashed" block>
              <IconifyIcon icon="ant-design:plus-outlined" />
              添加指标
            </a-button>

            <div v-if="specificationForm.metrics" class="metrics-list">
              <div
                v-for="(metric, index) in specificationForm.metrics"
                :key="index"
                class="metric-item"
              >
                <a-row :gutter="8">
                  <a-col :span="20">
                    <a-input
                      v-model:value="specificationForm.metrics[index]"
                      placeholder="指标名称"
                    />
                  </a-col>
                  <a-col :span="4">
                    <a-button type="text" danger @click="removeMetric(index)">
                      <IconifyIcon icon="ant-design:delete-outlined" />
                    </a-button>
                  </a-col>
                </a-row>
              </div>
            </div>
          </div>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 能力评估模态框 -->
    <a-modal
      v-model:open="evaluationModalVisible"
      title="能力评估"
      width="800px"
      :footer="null"
    >
      <div class="evaluation-content">
        <a-alert
          message="能力评估功能"
          description="这里将展示能力评估的详细结果，包括性能指标、可用性、安全性等维度的评估。"
          type="info"
          show-icon
          style="margin-bottom: 16px"
        />

        <a-card title="评估维度" size="small">
          <a-row :gutter="16">
            <a-col :span="6">
              <a-statistic title="性能" value="85" suffix="%" />
            </a-col>
            <a-col :span="6">
              <a-statistic title="可用性" value="92" suffix="%" />
            </a-col>
            <a-col :span="6">
              <a-statistic title="安全性" value="88" suffix="%" />
            </a-col>
            <a-col :span="6">
              <a-statistic title="合规性" value="95" suffix="%" />
            </a-col>
          </a-row>
        </a-card>

        <a-card title="评估详情" size="small" style="margin-top: 16px">
          <a-table
            :columns="evaluationColumns"
            :data-source="evaluationData"
            :pagination="false"
            size="small"
          />
        </a-card>
      </div>
    </a-modal>
  </div>
</template>

<style lang="less" scoped>
.resource-capability {
  .capability-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    h3 {
      margin: 0;
    }
  }

  .capability-card {
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .interfaces-section,
  .specifications-section {
    .interfaces-list,
    .specifications-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
      gap: 12px;
      margin-top: 12px;
    }

    .interface-card,
    .specification-card {
      .interface-title,
      .specification-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .interface-info,
      .specification-info {
        margin-bottom: 8px;

        p {
          margin: 4px 0;
          font-size: 12px;
        }
      }

      .interface-actions,
      .specification-actions {
        display: flex;
        gap: 4px;
      }
    }
  }

  .metrics-editor {
    .metrics-list {
      margin-top: 12px;

      .metric-item {
        margin-bottom: 8px;
        padding: 8px;
        border: 1px solid #f0f0f0;
        border-radius: 4px;
        background: #fafafa;
      }
    }
  }

  .evaluation-content {
    .ant-statistic {
      text-align: center;
    }
  }
}
</style>
